package com.aabte.design.pattern.behavioral.interpreter;

import java.util.Stack;

public class ExpressionParser {

    private Stack<Interpreter> stack = new Stack<>();

    public int parse(String inputStr) {
        String[] strItemArray = inputStr.split(" ");
        for (String symbol : strItemArray){
            if (!OperatorUtil.isOperator(symbol)) {
                Interpreter numberExpression = new NumberInterpreter(symbol);
                stack.push(numberExpression);
                System.out.println(String.format("入栈：%d", numberExpression.interpret()));
            } else {
                // 是运算符号可以计算
                Interpreter firstExpression = stack.pop();
                Interpreter secondExpression = stack.pop();
                System.out.println(String.format("出栈：%d 和 %d",
                        firstExpression.interpret(),
                        secondExpression.interpret()));
                Interpreter operator = OperatorUtil.getExpression(symbol, firstExpression, secondExpression);
                System.out.println(String.format("应用运算符：%s", operator.toString()));
                int result = operator.interpret();
                NumberInterpreter resultExpression = new NumberInterpreter(result);
                stack.push(resultExpression);
                System.out.println(String.format("阶段结果入栈：%d", resultExpression.interpret()));
            }
        }

        return stack.pop().interpret();

    }
}
